package org.ilovecode.display {
	
	import fl.controls.Button;
	import fl.controls.ComboBox;
	import fl.controls.DataGrid;
	import fl.controls.dataGridClasses.DataGridColumn;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextFormat;
	
	import org.ilovecode.Utilities;
	import org.ilovecode.events.ApartmentEvent;
	import org.ilovecode.screen.Screen;
	import org.ilovecode.screen.ScreenGroup;
	import org.ilovecode.screen.ScreenName;
	
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class SearchApartment extends Screen {
		
		//{ region Stage elements
		
		public var sizeComboBox:ComboBox;
		public var floorComboBox:ComboBox;
		public var roomComboBox:ComboBox;
		public var priceComboBox:ComboBox;
		public var warning:MovieClip;
		public var datagrid:DataGrid;
		
		//} endregion
		
		private var numComboBoxesLoaded:int = 0;
		
		public function SearchApartment() {
			super(ScreenName.SEARCH, ScreenGroup.APARTMENTS, "searchApartments");
		}
		
		override protected function initUI():void
		{
			super.initUI();
			
			Utilities.loadURL("http://www.centar-bundek.hr/xml/codelist/areainterval", loadSizeComboBox);
			Utilities.loadURL("http://www.centar-bundek.hr/xml/codelist/floor", loadFloorComboBox);
			Utilities.loadURL("http://www.centar-bundek.hr/xml/codelist/roomsnumber", loadRoomComboBox);
			Utilities.loadURL("http://www.centar-bundek.hr/xml/codelist/priceinterval", loadPriceComboBox);
			
			warning.visible = false;
			datagrid.visible = false;
			datagrid.removeAll();
			formatDataGrid();
		}
		
		override protected function addListeners():void
		{
			super.addListeners();
			sizeComboBox.addEventListener(Event.CHANGE, dataChange);
			floorComboBox.addEventListener(Event.CHANGE, dataChange);
			roomComboBox.addEventListener(Event.CHANGE, dataChange);
			priceComboBox.addEventListener(Event.CHANGE, dataChange);
			datagrid.addEventListener(Event.CHANGE, dataGridChange);
		}
		
		override protected function removeListeners():void
		{
			super.removeListeners();
			sizeComboBox.removeEventListener(Event.CHANGE, dataChange);
			floorComboBox.removeEventListener(Event.CHANGE, dataChange);
			roomComboBox.removeEventListener(Event.CHANGE, dataChange);
			priceComboBox.removeEventListener(Event.CHANGE, dataChange);
			datagrid.removeEventListener(Event.CHANGE, dataGridChange);
		}
		
		//{ region Loading
		
		private function loadSizeComboBox(event:Event):void {
			loadComboBoxData(XML(event.target.data), sizeComboBox);
			numComboBoxesLoaded++;
			checkIfAllComboBoxesAreLoaded();
		}
		
		private function loadFloorComboBox(event:Event):void {
			loadComboBoxData(XML(event.target.data), floorComboBox);
			numComboBoxesLoaded++;
			checkIfAllComboBoxesAreLoaded();
		}
		
		private function loadRoomComboBox(event:Event):void {
			loadComboBoxData(XML(event.target.data), roomComboBox);
			numComboBoxesLoaded++;
			checkIfAllComboBoxesAreLoaded();
		}
		
		private function loadPriceComboBox(event:Event):void {
			loadComboBoxData(XML(event.target.data), priceComboBox);
			numComboBoxesLoaded++;
			checkIfAllComboBoxesAreLoaded();
		}
		
		private function loadComboBoxData(xml:XML, cb:ComboBox):void {
			for each(var item:XML in xml.children()) {
				var o:Object = new Object();
				o.label = item.name;
				o.data = item.id;
				cb.addItem(o);
			}
			if (cb.numChildren > 0) {
				cb.selectedIndex = 0;
			}
		}
		
		private function checkIfAllComboBoxesAreLoaded():void {
			if (numComboBoxesLoaded >= 4) {
				loadResults();
			}
		}
		
		//} endregion
		
		//{ region Load results
		
		private function loadResults():void {
			var url:String =  "http://www.centar-bundek.hr/xml/search/" + floorComboBox.selectedItem.data + "/" + 
							   roomComboBox.selectedItem.data + "/" + sizeComboBox.selectedItem.data + "/" + priceComboBox.selectedItem.data;
			Utilities.loadURL(url, loadResultsComplete);
		}
		
		private function formatDataGrid():void {
			datagrid.width = this.width - 50;
			datagrid.height = this.height - 190;
			datagrid.move(25, 135);
			datagrid.rowHeight=25;
			datagrid.resizableColumns = true;
			var formatGrid:TextFormat = new TextFormat();
			formatGrid.color = 0x000000;
			formatGrid.size = 14;
			datagrid.setRendererStyle("textFormat",formatGrid);
			datagrid.setStyle("fontFamily", "Verdana");
			datagrid.setStyle("headerColor", "0xA6CBDD");
			datagrid.setStyle("alternatingRowColors", ["0xF0F0F0", "0xFFFFFF"]);
			datagrid.setStyle("rollOverColor", "0xDCEBF1");
			datagrid.setStyle("selectionColor", "0xFFF97D");
			datagrid.setStyle("selectionDuration", 300);
			datagrid.blendMode = "normal";
			
			var colA:DataGridColumn = new DataGridColumn("Površina");
			var colB:DataGridColumn = new DataGridColumn("Kat");
			var colC:DataGridColumn = new DataGridColumn("Broj soba");
			var colD:DataGridColumn = new DataGridColumn("Cijena");
			var colE:DataGridColumn = new DataGridColumn("Ukupna cijena");
			var colF:DataGridColumn = new DataGridColumn("Id");
			colF.visible = false;
			datagrid.addColumn(colA);
			datagrid.addColumn(colB);
			datagrid.addColumn(colC);
			datagrid.addColumn(colD);
			datagrid.addColumn(colE);
			datagrid.addColumn(colF);
		}
		
		private function loadResultsComplete(event:Event):void {
			var xml:XML = XML(event.target.data);
			
			if (xml.children().length() > 0) {
				warning.visible = false;
				for each(var item:XML in xml.children()) {
					var o:Object = new Object();
					//TODO: Promjeniti ukupnu cijenu da se uzme iz XML-a
					var price:Number = Number(String(item.stateprice).replace(",", "."));
					if (price != 0) {
						o["Kat"] = item.floor;
						o["Broj soba"] = item.roomsnumber;
						o["Površina"] = Number(item.area).toFixed(2) + " m2";
						o["Cijena"] = Utilities.getMoney(price, 2) + " EUR/m2";
						o["Ukupna cijena"] = Utilities.getMoney(price, 2) + " EUR";
						o["Id"] = item.id;
						datagrid.addItem(o);
					}
				}
				datagrid.visible = true;
			} else {
				warning.visible = true;
			}
		}
		
		//} endregion
		
		//{ region Handlers
		
		private function dataGridChange(event:Event):void {
			var o:Object = new Object();
			o.roomID = datagrid.selectedItem.Id;
			o.floorID = getFloorNumber(datagrid.selectedItem.Kat);
			//this.dispatchEvent(new ApartmentEvent(ApartmentEvent.SELECTED, o));
			controller.showApartment(datagrid.selectedItem.Id, getFloorNumber(datagrid.selectedItem.Kat), "search");
		}
		
		private function dataChange(event:Event):void {
			if (datagrid.visible) {
				datagrid.visible = false;
				warning.visible = false;
			}
			
			if (sizeComboBox.selectedIndex != -1 && roomComboBox.selectedIndex != -1 && floorComboBox.selectedIndex != -1) {
				datagrid.removeAll();
				loadResults();
			}
		}
		
		//} endregion
		
		private function loadXML(url:String, func:Function):void {
			var req:URLRequest = new URLRequest(url);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, func);
			loader.load(req);
		}
		
		private function getFloorNumber(floorName:String):int {
			var floorNumber:int = -1;
			switch(floorName) {
				case "prizemlje":
					floorNumber = 0;
					break;
				case "prvi kat":
					floorNumber = 1;
					break;
				case "drugi kat":
					floorNumber = 2;
					break;
				case "treći kat":
					floorNumber = 3;
					break;
				case "četvrti kat":
					floorNumber = 4;
					break;
				case "peti kat":
					floorNumber = 5;
					break;
				case "šesti kat":
					floorNumber = 6;
					break;
				case "sedmi kat":
					floorNumber = 7;
					break;
				case "osmi kat":
					floorNumber = 8;
					break;
			}
			
			return floorNumber;
		}
		
	}

}